package avicit.bdp.dds.server.worker.task.sqoop;

import avicit.bdp.dds.dispatch.process.Property;
import avicit.bdp.dds.dispatch.task.AbstractParameters;
import avicit.bdp.dds.dispatch.task.sqoop.SqoopParameters;
import avicit.bdp.dds.common.utils.ParameterUtils;
import avicit.bdp.dds.server.entity.TaskExecutionContext;
import avicit.bdp.dds.server.utils.ParamUtils;
import avicit.bdp.dds.server.worker.task.AbstractYarnTask;
import avicit.bdp.dds.server.worker.task.sqoop.generator.SqoopJobGenerator;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;

import java.util.Map;

/**
 * sqoop task extends the shell task
 */
public class SqoopTask extends AbstractYarnTask {

    private SqoopParameters sqoopParameters;

    /**
     * taskExecutionContext
     */
    private TaskExecutionContext taskExecutionContext;

    public SqoopTask(TaskExecutionContext taskExecutionContext, Logger logger){
        super(taskExecutionContext,logger);
        this.taskExecutionContext = taskExecutionContext;
    }

    @Override
    public void init() throws Exception {
        logger.info("sqoop task params {}", taskExecutionContext.getTaskParams());
        sqoopParameters =
                JSON.parseObject(taskExecutionContext.getTaskParams(),SqoopParameters.class);
        if (!sqoopParameters.checkParameters()) {
            throw new RuntimeException("sqoop task params is not valid");
        }

    }

    @Override
    protected String buildCommand() throws Exception {
        //get sqoop scripts
        SqoopJobGenerator generator = new SqoopJobGenerator();
        String script = generator.generateSqoopJob(sqoopParameters,taskExecutionContext);

        Map<String, Property> paramsMap = ParamUtils.convert(ParamUtils.getUserDefParamsMap(taskExecutionContext.getDefinedParams()),
                taskExecutionContext.getDefinedParams(),
                sqoopParameters.getLocalParametersMap(),
                taskExecutionContext.getCmdTypeIfComplement(),
                taskExecutionContext.getScheduleTime());

        if(paramsMap != null){
            String resultScripts = ParameterUtils.convertParameterPlaceholders(script,  ParamUtils.convert(paramsMap));
            logger.info("sqoop script: {}", resultScripts);
            return resultScripts;
        }

        return null;
    }

    @Override
    protected void setMainJarName() {
    }

    @Override
    public AbstractParameters getParameters() {
        return sqoopParameters;
    }
}
